import React, { useCallback, useState } from 'react';
import { Button, Card, List, Row, Col, Tag, notification } from 'antd';
import { LoadingOutlined, MessageOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import AuthComponent from '@/components/Authorized/AuthComponent';
import moment from 'moment';
import { useRequest } from '@umijs/hooks';
import { getMsgList } from '../../../service';
import styles from './index.less';
import Search from './Search';
import { parseMessage } from '@/pages/messageCenter/utils';
import { router } from 'umi';
import { parse } from 'querystring';

const size = 20;
const { CheckableTag } = Tag;

const History = ({ msgType }) => {
  const [date, setDate] = useState([]);
  const { loading, data, loadingMore, loadMore: runLoadMore } = useRequest(
    ({ pager = {} } = {}) => {
      const page = pager.currentPage ? pager.currentPage + 1 : 1;
      const [beginDate = '', endDate = ''] = (date || []).map(item => item.format('YYYY-MM-DD'));
      return msgType
        ? getMsgList({
            page,
            msgState: 3,
            size,
            beginDate,
            endDate,
          })
        : {};
    },
    {
      loadMore: true,
      initialData: { list: [] },
      refreshDeps: [msgType, date],
    },
  );

  const { list, pager: { currentPage, totalPages } = {} } = data;

  const onMessageCLick = useCallback(msg => {
    // if (msg.moduleUrl) {
    //   router.push({
    //     pathname: msg.moduleUrl,
    //   });
    // }
    if (msg.moduleUrl) {
      let resourceStr = window.localStorage.getItem('resource');
      // /banksearchSystem/inPortBaggageManagement/lessBaggageManagement 少收
      // /banksearchSystem/inPortBaggageManagement/internalMissingManagement 内务缺失
      //         AHL  少收；---行查子平台-进港少收行李管理；
      // LOS  内物缺失；---行查子平台-进港内物缺失管理；
      // 需要把事故单号带过去查询出查看的事故单展示在列表
      // 消息title   少收行李到期结案提醒
      if (msg.msgTitle === '少收行李到期结案提醒') {
        let toaccidentId = ''; //事故单号
        if(msg.msgContent.indexOf('AHL') > -1){
          if(resourceStr.indexOf('"path":"/banksearchSystem/inPortBaggageManagement/lessBaggageManagement') == -1){
            return  notification.info({
              message: '您当前无权限进行查看',
            });
          }
          let sliceStartIndex = msg.msgContent.indexOf('AHL')
          toaccidentId = msg.msgContent.slice(sliceStartIndex,sliceStartIndex+17);
          window.sessionStorage.setItem('isFromCompensate','1');
          router.push({
            pathname: '/banksearchSystem/inPortBaggageManagement/lessBaggageManagement',
            state: {
              accidentId: toaccidentId
            }
          });
        } 
        if(msg.msgContent.indexOf('LOS') > -1){
          if(resourceStr.indexOf('"path":"/banksearchSystem/inPortBaggageManagement/internalMissingManagement') == -1){
            return  notification.info({
              message: '您当前无权限进行查看',
            });
          }
          let sliceStartIndex = msg.msgContent.indexOf('LOS')
          toaccidentId = msg.msgContent.slice(sliceStartIndex,sliceStartIndex+17);
          window.sessionStorage.setItem('isFromCompensate','1');
          router.push({
            pathname: '/banksearchSystem/inPortBaggageManagement/internalMissingManagement',
            state: {
              accidentId: toaccidentId
            }
          });
        }
      }else{
        if(resourceStr.indexOf(`${msg.moduleUrl.split('?')[0]}`) == -1 || !AuthComponent.getAuth('compensation.audit.viewDetail')){
          return  notification.info({
            message: '您当前无权限进行查看',
          });
        };
        let query = {};
        if (~msg.moduleUrl.indexOf('?')) {
          query = parse(msg.moduleUrl.split('?')[1])
        };
        sessionStorage.setItem('firstLoad', '1');
        let sendDate = msg.msgDate.substring(0, 10);
        let compensationAuditState = { ...query,sendDate: sendDate,  flightDate: msg.flightDate, flightNo: msg.flightNo };
        window.localStorage.setItem('compensationAuditState',JSON.stringify(compensationAuditState));
        router.push({
          pathname: msg.moduleUrl.split('?')[0],
          state: compensationAuditState
        });
      }


      // let query = {}
      // if (~msg.moduleUrl.indexOf('?')) {
      //   query = parse(msg.moduleUrl.split('?')[1])
      // }
      // sessionStorage.setItem('firstLoad', '1')
      // router.push({
      //   pathname: msg.moduleUrl.split('?')[0],
      //   // query,
      //   state: { ...query, flightDate: msg.flightDate, flightNo: msg.flightNo }
      // });
    }
  }, []);

  const onSearch = useCallback(date => {
    setDate(date);
  });

  const loadMore = list.length > 0 && currentPage < totalPages && (
    <div
      style={{
        textAlign: 'center',
        marginTop: 16,
      }}
    >
      <Button
        onClick={runLoadMore}
        loading={loadingMore}
        style={{
          paddingLeft: 48,
          paddingRight: 48,
          marginBottom: 24,
        }}
      >
        {loading ? (
          <span>
            <LoadingOutlined /> 加载中...
          </span>
        ) : (
          '加载更多'
        )}
      </Button>
    </div>
  );

  return (
    <>
      <Row gutter={{ xs: 8, sm: 16, md: 24 }}>
        <Col span={16}>
          <List
            size="large"
            split={false}
            loading={list.length === 0 ? loading : false}
            rowKey="msgId"
            itemLayout="vertical"
            grid={{ gutter: 24, column: 1 }}
            loadMore={loadMore}
            dataSource={list}
            renderItem={item => (
              <List.Item key={item.msgId}>
                <Card
                  bordered={false}
                  title={
                    <span>
                      {item.msgState === 1 && (
                        <CheckableTag checked color="blue">
                          未读
                        </CheckableTag>
                      )}
                      {item.msgTitle}
                    </span>
                  }
                  extra={item.msgDate}
                  actions={[
                    <div
                      onClick={() => onMessageCLick(item)}
                      style={{ textAlign: 'left', padding: '0 24px' }}
                    >
                      <span>立即查看</span>
                      <span style={{ float: 'right' }}>&gt;</span>
                    </div>,
                  ]}
                >
                  <div className={styles.listContent}>
                    <div className={styles.description}>
                      {/* <p>
                        {item.flightDate}&nbsp;{item.flightNo}
                      </p> */}
                      {parseMessage(item.msgContent)}
                    </div>
                    {msgType === 'self' && (
                      <div className={styles.extra}>
                        <em>{moment(item.updatedAt).format('YYYY-MM-DD HH:mm')}</em>
                        <span style={{ float: 'right' }}>
                          <MessageOutlined
                            style={{
                              marginRight: 6,
                            }}
                          />
                          16条评论
                        </span>
                      </div>
                    )}
                  </div>
                </Card>
              </List.Item>
            )}
          />
        </Col>
        <Col span={8} style={{ height: '100%' }}>
          <Search onSearch={onSearch} />
        </Col>
      </Row>
    </>
  );
};

export default History;
